<?

function smarty_function_select_option( $obj, $text, $value, $selected ) {

	echo '<option value="' . $obj->$value . '"' .
			( $obj->$value == $selected ? ' selected="selected"' : '' ) .
			'>' .
			smarty_modifier_escape($obj->$text) .
		'</option>';

}

function smarty_function_select( $params, $smarty ) {

	$smarty->depend( 'modifier', 'escape' );

	$from = $params['from'];
	$text = $params['text'] ? $params['text'] : '';
	$value = $params['value'] ? $params['value'] : 'id';
	$selected = $params['selected'] ? $params['selected'] : false;
	$group = $params['group'];

	// add a label?
	if ( $label = $params['label'] ) {
		$smarty->depend( 'function', 'label' );
		smarty_function_label(array(
			'for' => $params['name'],
			text => $label,
			'class' => $params['labelClass']
		), $smarty );
	}

	echo Smutty_Smarty::htmlElement( 'select', array(
		name => Smutty_Smarty::getFieldName($params['name']),
		'class' => $params['class'],
		id => $params['id']
	), $smarty );
	echo '<option value=""></option>';

	foreach ( $from as $obj ) {
		// do we need to try and fine a text attribute?
		if ( !$text ) {
			$options = array( 'name', 'title', 'subject', 'id' );
			foreach ( $options as $option )
				if ( $obj->$option ) {
					$text = $option;
					break;
				}
		}
		// draw option groups?
		if ( $group ) {
			echo '<optgroup label="' . $obj->$text . '">';
			$obj2s = $obj->$group;
			foreach ( $obj2s as $obj2 )
				smarty_function_select_option( $obj2, $text, $value, $selected );
			echo '</optgroup>';
		}
		else smarty_function_select_option( $obj, $text, $value, $selected );
	}

	echo '</select>';

}

?>